﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using AppCompress.Utils;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;
using AppCompress.Model;

namespace AppCompress
{
    public partial class Form1 : Form
    {
        private bool check = false;
        private FileUtils fileUtils = new FileUtils();
        private CancellationTokenSource tokenSource = new CancellationTokenSource(); //线程中止
        private ProgressIndicate progress = new ProgressIndicate(30, "正在加载文件...");
        private string temporaryPath = @"C:\Users\lbt\Desktop\";

        public Form1()
        {
            InitializeComponent();
        }

        private void selectFileButton_Click(object sender, EventArgs e)
        {
            folderBrowserDialogOfSelect.Description = "请选择文件夹";
            folderBrowserDialogOfSelect.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialogOfSelect.ShowNewFolderButton = true;
            if (historySelect.Text.Length > 0)
            {
                folderBrowserDialogOfSelect.SelectedPath = historySelect.Text;
            }
            if (folderBrowserDialogOfSelect.ShowDialog() == DialogResult.OK)
            {
                treeView1.Nodes.Clear();
                if (!historySelect.Items.Contains(folderBrowserDialogOfSelect.SelectedPath))
                {
                    historySelect.Items.Add(folderBrowserDialogOfSelect.SelectedPath);
                }
                historySelect.Text = folderBrowserDialogOfSelect.SelectedPath;
            }
        }

        /// <summary>
        /// 展示目录结构
        /// </summary>
        public void showTreeView()
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(historySelect.Text);
            List<Model.File> allFile = fileUtils.GetAllFileInfo(directoryInfo);
            for (int i = 0; i < allFile.Count; i++)
            {
                Model.File file = allFile[i];
                TreeNode tn = new TreeNode(file.Name);
                tn.Name = file.Path;
                this.treeView1.ExpandAll();
                this.treeView1.Nodes.Add(tn);
                Bianli(file, tn);
                treeView1.ExpandAll();
            }
        }

        /// <summary>
        /// 根据根文件节点去寻找所有子节点，并装载node
        /// </summary>
        /// <param name="file"></param>
        /// <param name="node1">父节点</param>
        public void Bianli(Model.File file, TreeNode node1)
        {
            TreeNode node = node1;
            if (file.IsDirectory == 1)
            {
                TreeNode node2 = node;
                //排除根节点
                if (file.ParentFile != null && file.ParentFile.IsDirectory == 1)
                {
                    node2 = new TreeNode(file.Name);
                    node2.Name = file.Path;
                    node.Nodes.Add(node2);
                }
                for (int i = 0; i < file.FileInfos.Count; i++)
                {
                    Bianli(file.FileInfos[i], node2);
                }
            }
            else
            {
                node.Nodes.Add(file.Name);
                node.Nodes[node.Nodes.Count - 1].Name = file.Path;
            }
        }

        /// <summary>
        /// 多选框选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TV_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (!check)
                fileUtils.setchild(e.Node, ref check);
            fileUtils.setparent(e.Node);
            check = false;
        }

        /// <summary>
        /// 压缩按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            TreeNodeCollection treeNodes = treeView1.Nodes;
            string sourceDirectory = historySelect.Text;
            folderBrowserDialogOfTargetPath.Description = "请选择压缩到的文件夹";
            folderBrowserDialogOfTargetPath.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialogOfTargetPath.ShowNewFolderButton = true;
            if (historySelect.Text.Length > 0)
            {
                folderBrowserDialogOfTargetPath.SelectedPath = historySelect.Text;
            }
            if (folderBrowserDialogOfTargetPath.ShowDialog() == DialogResult.OK)
            {
                temporaryPath = folderBrowserDialogOfTargetPath.SelectedPath;
                label4.Text = "压缩到：" + temporaryPath;
                Task.Factory.StartNew(() =>
                {
                    compress(sourceDirectory, treeNodes);
                });
            }
        }

        private void compress(string source, TreeNodeCollection treeNode)
        {
            long start = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
            if (treeNode.Count <= 0)
            {
                MessageBox.Show("请先选择对应文件！");
                return;
            }
            string sourceDirectory = source; //源文件路径
            byte isCreateFile = 0;
            List<TreeNode> treeNodes;
            if (!treeNode[0].Checked)
            {
                treeNodes = fileUtils.GetSelectedFile(treeNode[0]); //根节点
                if (treeNodes.Count > 0)
                {
                    workTask(progress);
                    //复制所有文件到新的路径
                    sourceDirectory = fileUtils.CopyAndCreate(treeNodes, treeNode[0]);
                    isCreateFile = 1;
                }
                else
                {
                    MessageBox.Show("请先选中需要压缩的文件！");
                    return;
                }
            }

            Random random = new Random();
            progress = new ProgressIndicate(random.Next(4, 7) * 10, "正在压缩中，请稍后...");
            workTask(progress);
            try
            {
                CompressUtil.Compressing(temporaryPath + @"\" + treeNode[0].Text + ".zip", sourceDirectory);
                long end = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
                //删除临时文件
                if (isCreateFile == 1)
                {
                    Directory.Delete(sourceDirectory, true);
                }
                workTask();
                progress = new ProgressIndicate(100, "压缩完成！共耗时：" + (end - start) + "ms" + "\n压缩目标路径：" + temporaryPath);
                workTask(progress);
            }
            catch (Exception ex)
            {
                resetProgress();
                MessageBox.Show(ex.Message);
            }
        }

        private void historySelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            try
            {
                showTreeView();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void resetProgress()
        {
            label3.Text = "";
            progressBar1.Value = 0;
        }

        /// <summary>
        /// 修改进度条状态
        /// </summary>
        /// <param name="progress"></param>
        private void workTask(ProgressIndicate progress)
        {
            this.BeginInvoke(new EventHandler((sender, e) =>
            {
                progressBar1.Value = progress.Num;
                label3.Text = progress.Description;
            }), null);
        }

        private void workTask()
        {
            this.BeginInvoke(new EventHandler((sender, e) =>
            {
                label4.Text = "";
            }), null);
        }

        public void SetTreeViewList(TreeNode nodes)
        {
            //有子节点
            foreach (TreeNode newNode in nodes.Nodes)
            {
                if (newNode.Nodes.Count > 0)
                {
                    SetTreeViewList(newNode);
                }
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            MessageBox.Show("选中" + treeView1.SelectedNode.Name);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.BeginInvoke(new EventHandler((sender1, e1) =>
            {
                progressBar1.Value = 20;
            }), null);
        }

        private void historySelect_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                treeView1.Nodes.Clear();
                // 验证路径是否正确
                if (fileUtils.checkoutPath(historySelect.Text))
                {
                    // 验证是否存在目录
                    if (Directory.Exists(historySelect.Text))
                    {
                        try
                        {
                            showTreeView();
                            if (!historySelect.Items.Contains(historySelect.Text))
                            {
                                historySelect.Items.Add(historySelect.Text);
                            }
                        }
                        catch (Exception e1)
                        {
                            MessageBox.Show(e1.Message);
                        }
                    }
                    else
                    {
                        MessageBox.Show("不存在此文件夹");
                    }
                }
            }
        }
    }
}